package com.zengjianjun.hadoop.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;
import sun.security.action.GetPropertyAction;

import java.io.File;
import java.security.AccessController;

/**
 * @author zengjianjun
 */
@Slf4j
public class FileUtil {

    /**
     * MultipartFile转换为File
     * 转换后的文件名称默认使用MultipartFile的文件名称
     *
     * @param multipartFile 文件信息
     * @return  {@link File}
     */
    public static File transferToFile(@NotNull MultipartFile multipartFile) {
        return transferToFile(multipartFile, null);
    }

    /**
     * MultipartFile转换为File
     *
     * @param multipartFile 文件信息
     * @return  {@link File}
     */
    public static File transferToFile(@NotNull MultipartFile multipartFile, String fileName) {
        try {
            if (StringUtils.isEmpty(fileName)) {
                fileName = multipartFile.getOriginalFilename();
                if (StringUtils.isEmpty(fileName)) {
                    throw new IllegalArgumentException("文件信息错误");
                }
            }
            File tmpdir = new File(AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir")));
            File file = new File(tmpdir, fileName);
            multipartFile.transferTo(file);
            file.deleteOnExit();
            return file;
        } catch (Exception e) {
            log.error("FileUtil.transferToFile error:", e);
            return null;
        }
    }
}
